<template>
  <view class="mine-container">
    <!-- 用户信息卡片 -->
    <view class="user-profile">
      <view class="blur-bg"></view>
      <view class="user-info">
        <view class="avatar-container" @click="navigateToProfile">
          <image
            class="avatar"
            :src="isLogin && userInfo && userInfo.avatar ? userInfo.avatar : defaultAvatar"
            mode="aspectFill"
          />
          <view v-if="isLogin" class="avatar-edit">
            <wd-icon name="edit-pen" size="16" color="#165dff" />
          </view>
        </view>
        <view class="user-details">
          <block v-if="isLogin">
            <view class="nickname">
              {{ userInfo && userInfo.nickname ? userInfo.nickname : "匿名用户" }}
            </view>
            <view class="user-id">
              ID: {{ userInfo && userInfo.username ? userInfo.username : "0000000" }}
            </view>
          </block>
          <block v-else>
            <view class="login-prompt">立即登录获取更多功能</view>
            <wd-button class="login-btn" size="small" type="primary" @click="navigateToLoginPage">
              登录/注册
            </wd-button>
          </block>
        </view>
        <view class="actions">
          <view class="action-btn" @click="navigateToSettings">
            <wd-icon name="setting1" size="22" color="#165dff" />
          </view>
          <view v-if="isLogin" class="action-btn" @click="navigateToSection('messages')">
            <wd-icon name="chat1" size="22" color="#165dff" />
            <!-- <view v-if="true" class="badge">2</view> -->
          </view>
        </view>
      </view>
    </view>

    <!-- 数据统计 -->
    <!-- <view class="stats-container">
      <view class="stat-item" @click="navigateToSection('family')">
        <view class="stat-value">{{ familyStats.familyCount }}</view>
        <view class="stat-label">我的家族</view>
      </view>
      <view class="divider"></view>
      <view class="stat-item" @click="navigateToSection('member')">
        <view class="stat-value">{{ familyStats.memberCount }}</view>
        <view class="stat-label">家族成员</view>
      </view>
      <view class="divider"></view>
      <view class="stat-item" @click="navigateToSection('relation')">
        <view class="stat-value">{{ familyStats.relationCount }}</view>
        <view class="stat-label">关系数量</view>
      </view>
    </view> -->

    <!-- 家谱管理 -->
    <view class="card-container">
      <view class="card-header">
        <view class="card-title">
          <wd-icon name="tree" size="18" color="#165dff" />
          <text>家谱管理</text>
        </view>
      </view>
      <view class="tools-grid">
        <view class="tool-item" @click="navigateToDetail(userInfo && userInfo.userId)">
          <view class="tool-icon">
            <wd-icon name="home" size="24" color="#165dff" />
          </view>
          <view class="tool-label">
            {{ userInfo && userInfo.userId == 2 ? "家谱管理" : "我的家谱" }}
          </view>
        </view>
        <view
          v-if="userInfo && (userInfo.areaCodeScope == 6 || userInfo.areaCodeScope == 2)"
          class="tool-item"
          @click="navigateToSection('member')"
        >
          <view class="tool-icon">
            <wd-icon name="user" size="24" color="#165dff" />
          </view>
          <view class="tool-label">家谱成员</view>
        </view>
        <!-- 审核管理 -->
        <view
          v-if="userInfo && (userInfo.areaCodeScope == 6 || userInfo.areaCodeScope == 2)"
          class="tool-item"
          @click="navigateToSection('process')"
        >
          <view class="tool-icon">
            <wd-icon name="secured" size="22px" color="#165dff" />
          </view>
          <view class="tool-label">审核管理</view>
        </view>
        <!-- 二维码分享 -->
        <view class="tool-item" @click="handleShareQrCode">
          <view class="tool-icon">
            <wd-icon name="share" size="22px" color="#165dff" />
          </view>
          <view class="tool-label">二维码分享</view>
        </view>
      </view>
    </view>

    <!-- 常用工具 -->
    <view class="card-container">
      <view class="card-header">
        <view class="card-title">
          <wd-icon name="tools" size="18" color="#165dff" />
          <text>常用工具</text>
        </view>
      </view>
      <view class="tools-grid">
        <view class="tool-item" @click="navigateToProfile">
          <view class="tool-icon">
            <wd-icon name="user" size="24" color="#165dff" />
          </view>
          <view class="tool-label">个人资料</view>
        </view>
        <view class="tool-item" @click="navigateToSection('history')">
          <view class="tool-icon">
            <wd-icon name="time" size="24" color="#165dff" />
          </view>
          <view class="tool-label">浏览历史</view>
        </view>
        <view class="tool-item" @click="navigateToFAQ">
          <view class="tool-icon">
            <wd-icon name="help-circle" size="24" color="#165dff" />
          </view>
          <view class="tool-label">常见问题</view>
        </view>
        <view class="tool-item" @click="handleQuestionFeedback">
          <view class="tool-icon">
            <wd-icon name="check-circle" size="24" color="#165dff" />
          </view>
          <view class="tool-label">问题反馈</view>
        </view>
      </view>
    </view>
    <view v-if="isLogin" class="logout-btn-container">
      <view class="logout-btn" @click="handleLogout">退出登录</view>
    </view>
    <wd-toast />
  </view>
  <Share ref="shareRef"></Share>
</template>

<script lang="ts" setup>
import { useToast } from "wot-design-uni";
import { ref, computed, onMounted } from "vue";
import { getUserInfo, clearAll } from "@/utils/cache";
import Share from "@/pages/mine/components/share.vue";
const shareRef = ref<InstanceType<typeof Share>>();

const toast = useToast();
const userInfo = ref<any>(null);
const isLogin = computed(() => !!userInfo.value);
const defaultAvatar =
  "https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/fa6cbef09f834c41b7121841f6a9564e.png";

// 家族统计数据
const familyStats = ref({
  familyCount: 0,
  memberCount: 0,
  relationCount: 0,
});
const handleShareQrCode = async () => {
  if (shareRef.value) {
    await shareRef.value.createProductSharePoster();
  }
};
// 登录
const navigateToLoginPage = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const currentPagePath = `/${currentPage.route}`;

  uni.navigateTo({
    url: `/pages/login/index?redirect=${encodeURIComponent(currentPagePath)}`,
  });
};

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: "提示",
    content: "确认退出登录吗？",
    success: function (res) {
      if (res.confirm) {
        clearAll();
        userInfo.value = null;
        toast.show("已退出登录");
      }
    },
  });
};

// 个人信息
const navigateToProfile = () => {
  if (!isLogin.value) {
    navigateToLoginPage();
    return;
  }
  uni.navigateTo({ url: "/pages/mine/profile/index" });
};

// 常见问题
const navigateToFAQ = () => {
  uni.navigateTo({ url: "/pages/mine/faq/index" });
};

// 设置
const navigateToSettings = () => {
  uni.navigateTo({ url: "/pages/mine/settings/index" });
};

// 问题反馈
const handleQuestionFeedback = () => {
  uni.navigateTo({ url: "/pages/mine/feedback/index" });
};
// 我的家谱详情
const navigateToDetail = (userId: number | undefined) => {
  if (userId == 2) {
    uni.navigateTo({ url: "/pages/genealogy/index" });
  } else if (userId !== undefined) {
    uni.navigateTo({ url: `/pages/genealogy/detail?from=myFamily&userId=${userId}` });
  }
};
// 导航到各个板块
const navigateToSection = (section: string, subSection?: string) => {
  if (!isLogin.value) {
    navigateToLoginPage();
    return;
  }
  const sections: Record<string, string> = {
    messages: "消息中心",
    family: "家族管理",
    member: "成员管理",
    process: "审核列表",
    history: "浏览历史",
  };

  const urls: Record<string, string> = {
    family: "/pages/genealogy/index",
    member: "/pages/genealogy/person/index",
    process: "/pages/mine/process/index",
    history: "/pages/mine/history/index",
  };

  if (urls[section]) {
    uni.navigateTo({ url: urls[section] });
  } else {
    let message = sections[section];
    if (subSection) {
      message += ` - ${subSection}`;
    }
    toast.show(`${message}功能开发中...`);
  }
};

// 加载家族统计数据
const loadFamilyStats = async () => {
  try {
    // TODO: 调用API获取家族统计数据
    familyStats.value = {
      familyCount: 3,
      memberCount: 25,
      relationCount: 48,
    };
  } catch (error) {
    console.error("加载家族统计数据失败:", error);
  }
};

// 初始化页面，从本地缓存获取用户信息
const initPage = () => {
  userInfo.value = getUserInfo();
};

onMounted(() => {
  initPage();
  if (isLogin.value) {
    loadFamilyStats();
  }
});
</script>

<style lang="scss" scoped>
.mine-container {
  padding-bottom: 100rpx;
  background-color: #f5f7fa;
}

// 用户信息卡片
.user-profile {
  position: relative;
  padding: 30rpx;
  overflow: hidden;

  .blur-bg {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    z-index: 0;
    height: 240rpx;
    background: linear-gradient(to bottom, #165dff, #d0deff);
    // background-color: #3eaf7c; /* 替换CSS变量为具体颜色值 */
  }

  .user-info {
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;

    .avatar-container {
      position: relative;

      .avatar {
        width: 120rpx;
        height: 120rpx;
        border: 4rpx solid rgba(255, 255, 255, 0.8);
        border-radius: 50%;
        /* 简化box-shadow以提高小程序兼容性 */
        box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
      }

      .avatar-edit {
        position: absolute;
        right: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36rpx;
        height: 36rpx;
        background-color: #165dff;
        border-radius: 50%;
        /* 简化box-shadow以提高小程序兼容性 */
        box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
      }
    }

    .user-details {
      flex: 1;
      margin-left: 24rpx;

      .nickname {
        margin-bottom: 8rpx;
        font-size: 34rpx;
        font-weight: bold;
        color: #fff;
      }

      .user-id {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.8);
      }

      .login-prompt {
        margin-bottom: 16rpx;
        font-size: 28rpx;
        color: #fff;
      }

      .login-btn {
        width: 160rpx;
        height: 60rpx;
        font-size: 26rpx;
        color: #165dff; /* 替换CSS变量为具体颜色值 */
        background-color: #fff;
        border: none;
        border-radius: 30rpx;
      }
    }

    .actions {
      display: flex;

      .action-btn {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 70rpx;
        height: 70rpx;
        margin-left: 16rpx;
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        /* 简化box-shadow以提高小程序兼容性 */
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .badge {
          position: absolute;
          top: -6rpx;
          right: -6rpx;
          z-index: 2;
          min-width: 32rpx;
          height: 32rpx;
          padding: 0 6rpx;
          font-size: 20rpx;
          line-height: 32rpx;
          color: #fff;
          text-align: center;
          background-color: #ff4d4f;
          border: 2rpx solid #fff;
          border-radius: 16rpx;
        }
      }
    }
  }
}

// 数据统计
.stats-container {
  display: flex;
  padding: 30rpx 20rpx;
  margin: 20rpx 30rpx;
  background: #fff;
  border-radius: 16rpx;
  /* 简化box-shadow以提高小程序兼容性 */
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.04);

  .stat-item {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: center;

    .stat-value {
      margin-bottom: 8rpx;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .stat-label {
      font-size: 26rpx;
      color: #666;
    }
  }

  .divider {
    width: 1px;
    margin: 0 20rpx;
    background-color: #eee;
  }
}

// 卡片容器通用样式
.card-container {
  margin: 24rpx 30rpx;
  overflow: hidden;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.04);

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 24rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .card-title {
      display: flex;
      align-items: center;

      text {
        margin-left: 12rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .card-action {
      display: flex;
      align-items: center;

      text {
        margin-right: 8rpx;
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

// 工具网格
.tools-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0 10rpx;

  .tool-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 25%;
    margin-bottom: 30rpx;

    .tool-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 90rpx;
      height: 90rpx;
      margin-bottom: 12rpx;
      background-color: rgb(184 184 184 / 8%); /* 替换CSS变量为具体颜色值 */
      border-radius: 18rpx;
    }

    /* 微信小程序触摸效果 */
    .tool-item:active .tool-icon {
      transform: scale(0.95);
    }

    .tool-label {
      font-size: 24rpx;
      color: #555;
    }
  }
}
.logout-btn {
  width: 100%;
  height: 80rpx;
  font-size: 28rpx;
  color: #666 !important;
  background-color: #f5f5f5 !important;
  border: none;
  border-radius: 40rpx;
  /* 微信小程序触摸效果 */
  opacity: 1;
  transition: opacity 0.2s;
  text-align: center;
  line-height: 80rpx;
}
// 退出登录按钮
.logout-btn-container {
  margin: 60rpx 30rpx;
}
</style>
